package com.szholly.pro.watergas_server.ps.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.util.RedisDbExecute;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.MessageException;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.ps.service.RemoteService;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import lrq.common.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/RemoteControl/*")
public class RemoteControlController extends BaseController { 
	
	@Autowired
	RemoteService remoteService;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 根据污水处理厂id和进出口状态，获取站房运行状态和仪器信息
	 * gislin
	 * 2015年11月13日
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getStationInfo")
	public void getStationInfo(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		String mn = RequestUnit.getString("mn");
		
		HashMap<String, RowBase> readDataList = remoteService.getStationRealTimeData(mn);
		List<RowBase> stationHouseData = remoteService.getStationHouseData(mn);
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("parmData", JSONObject.fromObject(readDataList).toString());
		jsonObj.put("mnInfo", DataUtil.listToJSONObject(stationHouseData));
		
		String result = jsonObj.toString();

		if (result == null)
			return;

		outString(result);
	}
	
	
	/**
	 * 获取指定站点所有设备的信息以及控制命令，为远程控制服务
	 * gislin
	 * 2016年1月6日
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/queryDeviceStatusByStationId")
	public void getDeviceStatusByStationId(HttpServletRequest resq, HttpServletResponse res){
		String mn = RequestUnit.getString("mn");
		
		String NH3_STATUS = "stationInfo:"+mn+":deviceInfo:060_STATUS";
		String TPTN_STATUS = "stationInfo:"+mn+":deviceInfo:101_STATUS";
		String COD_STATUS = "stationInfo:"+mn+":deviceInfo:111_STATUS";
		String SYE_CYCLE_SET = "stationInfo:"+mn+":sysStatus:SYS_CYCLE_SET";
		String NH3 = RedisDbExecute.getString(NH3_STATUS);
		String TPTN = RedisDbExecute.getString(TPTN_STATUS);
		String COD = RedisDbExecute.getString(COD_STATUS);
		String CYCLE = RedisDbExecute.getString(SYE_CYCLE_SET);
		HashMap<String, Object> result1 = new HashMap<>();
		HashMap<String, Object> result2 = new HashMap<>();
		
		if(CYCLE != null){
			int index = CYCLE.indexOf(".");
			CYCLE = CYCLE.substring(0, index)+" 小时";
		}		

		HashMap<String, HashMap<String,Object>> list = new HashMap<>();
		if("1.0".equals(NH3)) {
			result1.put("status", "关闭");
		} else 	if("3.0".equals(NH3)) {
			result1.put("status", "空闲");
		} else if("4.0".equals(NH3)) {
			result1.put("status", "正在测量");
		} else if("2.0".equals(NH3)){
			result1.put("status", "故障");
		} else {
			result1.put("status", "空闲");
		}
		result2.put("cycle", CYCLE);
		list.put("060",result1);
		list.put("060-cycle",result2);
		result1 = new HashMap<>();
		if("1.0".equals(TPTN)) {
			result1.put("status", "关闭");
		} else if("2.0".equals(TPTN)) {
			result1.put("status", "故障");
		} else if("3.0".equals(TPTN)) {
			result1.put("status", "空闲");
		} else if("4.0".equals(TPTN)) {
			result1.put("status", "正在测量");
		} else {
			result1.put("status", "空闲");
		}
		list.put("101",result1);
		list.put("101-cycle",result2);
		result1 = new HashMap<>();
		if("1.0".equals(COD)) {
			result1.put("status", "关闭");
		} else if("2.0".equals(COD)) {
			result1.put("status", "故障");
		} else if("3.0".equals(COD)) {
			result1.put("status", "空闲");
		} else if("4.0".equals(COD)) {
			result1.put("status", "正在测量");
		} else {
			result1.put("status", "空闲");
		} 
		list.put("111",result1);
		list.put("111-cycle",result2);
		result1 = new HashMap<>();
		String jsonObj = DataUtil.objectToJsonObject(list).toString();
		outString(jsonObj);
	}
	
	/**
	 * 发送命令,格式：pollId=011,attr=CLEAR,value=1;pollId=001,attr=CLEAR,value=0;
	 * gislin
	 * 2016年1月13日
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/sendOrder")
	public void sendOrder(HttpServletRequest resq, HttpServletResponse res){
		String orders = RequestUnit.getString("orders");
		String deviceId = RequestUnit.getString("deviceId");
		if(deviceId == null || deviceId.trim().equals("") || deviceId.equals("null")){
			deviceId = null;
		}
		String mn = RequestUnit.getString("mn");
		List<String> qns = remoteService.sendOrders(mn,deviceId, orders);
		String qnsStr = JSONArray.fromObject(qns).toString();
		outString(qnsStr);
	}
	
	/**
	 * 获取控制日志
	 * gislin
	 * 2015年11月16日
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getControlLog")
	public void getControlLog(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		String mn = RequestUnit.getString("mn");
		String startDate = RequestUnit.getString("startDate");
		String endDate = RequestUnit.getString("endDate");
		
		String sql = " SELECT * FROM REMOVE_CONTROL_ORDER WHERE MN = @MN ";
		
		if(!StringUtil.isEmpty(startDate)){
			sql += " and create_time >= to_date('" + startDate + "','YYYY-MM-DD') ";
		}
		if(!StringUtil.isEmpty(endDate)){
			sql += " and create_time <= to_date('" + endDate + "','YYYY-MM-DD') ";
		}
		
		sql +=" order by CREATE_TIME DESC ";
		
		List<GlobalParameter> pc = new ArrayList<>();
		pc.add(new GlobalParameter("MN", mn));
		
		String result = DataUtil.getPageSelectJson(sql, pc);
		outString(result);
	}
	
	/**
	 * 获取设备联网日志
	 * gislin
	 * 2015年11月16日
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getOnlineLog")
	public void getOnlineLog(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		String mn = RequestUnit.getString("mn");
		String startDate=RequestUnit.getString("startDate");
		String endDate=RequestUnit.getString("endDate");
		String sql = " SELECT * FROM MONITOR_ABNORMAL t \n "
				+ " WHERE t.MN = @MN AND t.offline_time is not null \n"
				+ " and (t.online_time is not null and (t.online_time - t.offline_time) > 0.007) \n";
		if(startDate!=null&&!"".equals(startDate)){
			 sql+="and t.offline_time>=to_date('"+startDate+" 00:00:00','yyyy-mm-dd hh24:mi:ss')";
		}
		if(endDate!=null&&!"".equals(endDate)){
			 sql+="and t.online_time<=to_date('"+endDate+" 23:59:59','yyyy-mm-dd hh24:mi:ss')";
		}
			 sql+= " order by CREATETIME DESC ";
		List<GlobalParameter> pc = new ArrayList<>();
		pc.add(new GlobalParameter("MN", mn));
		
		String result = DataUtil.getPageSelectJson(sql, pc);
		outString(result);
	}
	
	/**
	 * 获取质控日志
	 * gislin
	 * 2016年5月9日
	 * @param resq
	 * @param res
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getQualityLog")
	public void getQualityLog(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		String mn = RequestUnit.getString("mn");
		String startDate = RequestUnit.getString("startDate");
		String endDate = RequestUnit.getString("endDate");
		String parmName = RequestUnit.getString("parmName");
		List<GlobalParameter> pc = new ArrayList<>();
		String sql = " SELECT case quality_type when 'PXY' then '平行样' when 'ZKY' then '标样核查' when 'JBHX' then '加标回收' end qualityType,MEAS,"
				+" case result_flag when '0.0' then '合格' when '1.0' then '不合格' end result_flag, \n"
				+ " dd.s_domaincaption pollName,t.result,t.datatime from monitor_quality t "
				+ "	left join data_defulatdomain dd on t.parmname = dd.s_domaincode and dd.s_domainname = 'MONITOR_PARAM' "
				+ " where t.mn=@mn  \n";
		if(!StringUtil.isEmpty(parmName)){
			sql += " and dd.s_domaincaption like @parmName";
			GlobalParameter parmNameParm = new GlobalParameter("parmName", "%" + parmName + "%");
			pc.add(parmNameParm);
		}
		if(!StringUtil.isEmpty(startDate)){
			sql += " and createtime >= to_date('" + startDate + "','YYYY-MM-DD') ";
		}
		if(!StringUtil.isEmpty(endDate)){
			sql += " and createtime <= to_date('" + endDate + "','YYYY-MM-DD') ";
		}
		sql +=" order by pollname desc,t.datatime desc ";
		pc.add(new GlobalParameter("mn", mn));
		String result = DataUtil.getPageSelectJson(sql, pc);
		outString(result);
	}
	
	/**
	 * 获取指定设备配置的命令，为在线检测设备编辑用
	 * gislin
	 * 2016年1月5日
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/getDeviceOrderByDeviceid")
	public void getDeviceOrderByDeviceid(HttpServletRequest resq, HttpServletResponse res){
		String deviceId = RequestUnit.getString("deviceId");
		
		List<RowBase> list = remoteService.getMonitorDeviceOrdersByDeviceId(deviceId);
		String result = DataUtil.listToJSONObject(list).toString();
		outString(result);
	}
	
	/**
	 * 获取指定站点所有设备的信息以及控制命令，为远程控制服务
	 * gislin
	 * 2016年1月6日
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/getDeviceOrderByStationId")
	public void getDeviceOrderByStationId(HttpServletRequest resq, HttpServletResponse res){
		String stationId = RequestUnit.getString("stationId");
		String mn = RequestUnit.getString("mn");
		HashMap<String, HashMap<String,Object>> list = remoteService.getMonitorDeviceOrders(stationId,mn);
		String result = DataUtil.objectToJsonObject(list).toString();
		outString(result);
	}
	
	/**
	 * 更新指定设备对应的命令集
	 * gislin
	 * 2016年1月5日
	 * @param resq
	 * @param res
	 * @throws MessageException 
	 */
	@RequestMapping(value = "/updateDeviceOrders")
	public void updateDeviceOrders(HttpServletRequest resq, HttpServletResponse res) throws MessageException{
		String deviceId = RequestUnit.getString("deviceId");
		String orders = RequestUnit.getString("orders");
		remoteService.updateDeviceOrders(deviceId, orders);
	}
	
	/**
	 * 获取站点对应参数的质控配置，用于在质控管理中，显示配置
	 * gislin
	 * 2016年4月21日
	 */
	@RequestMapping(value = "/getQualityConfig")
	public void getQualityConfig(HttpServletRequest resq, HttpServletResponse res){
		String mn = RequestUnit.getString("mn");
		String pollName = RequestUnit.getString("pollName");
		HashMap<String, String> result = remoteService.getQualityConfig(mn, pollName);
		JSONObject jsonObj = JSONObject.fromObject(result);
		String json = jsonObj.toString();
		outString(json);
	}
	
	/**
	 * 获取站点污染物列表
	 * gislin
	 * 2016年3月1日
	 */
	@RequestMapping(value = "/getStationDevices")
	public void getStationPoll(HttpServletRequest resq, HttpServletResponse res){
		String stationId = RequestUnit.getParameter("stationId");
		List<RowBase> result = remoteService.getMonitorDeviceByStation(stationId);
		String resultStr = DataUtil.objectToJsonObject(result).toString();
		outString(resultStr);
	}
	
	/**
	 * 获取站点设备状态信息
	 * gislin
	 * 2016年3月1日
	 */
	@RequestMapping(value = "/getStationDevicesInfo")
	public void getStationDevicesInfo(HttpServletRequest resq, HttpServletResponse res){
		String mn = RequestUnit.getParameter("mn");
		HashMap<String, HashMap<String,String>> result = remoteService.getDeviceInfo(mn);
		String resultStr = DataUtil.objectToJsonObject(result).toString();
		outString(resultStr);
	}
	/**
	 * 记录发送系统测量周期命令
	 */
	@RequestMapping(value="/insertSendCycleLog") 
	public void insertSendCycleLog(HttpServletRequest resq, HttpServletResponse res){
		try {
			String mn = RequestUnit.getParameter("MN");
			String operationItem = RequestUnit.getParameter("OPERATION_ITEM");
			String operator = getCurrentUserJsonString();
			int endIndex = operator.indexOf(",");
			operator = operator.substring(18, endIndex-1);
			remoteService.insertSysCycleSetLog(mn,operationItem,operator);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
